SMS.controller('SMSController',
function SMSController($scope, $rootScope, $routeParams, utils, globals, model, notifications)
{
    $("#SMSMediaBrowser").layout($scope.layoutThreeColumns);

    $rootScope.mediaElement = [];
    $scope.settings = globals.settings;
    $scope.itemType = 'ss';
    $scope.index = [];
    $scope.selectedIndex;
    $scope.shortcut = [];
    $scope.directory = [];
    $scope.selectedDirectory;
    $scope.Server = globals.settings.Server;
    $scope.MediaBrowserSort = [
        { id: "newest", name: "Recently Added" },
        { id: "frequent", name: "Most Played" },
        { id: "recent", name: "Recently Played" }
    ];
    $scope.selectedMediaBrowserSort;
    $scope.Layouts = [
        { id: "list", name: "List" },
        { id: "grid", name: "Grid" }
    ];
    $scope.selectedLayout = globals.settings.DefaultLibraryLayout;

    $scope.rescanLibrary = function () {
        $.ajax({
            url: globals.BaseURL() + '/getUser.view?' + globals.BaseParams() + '&username=' + globals.settings.Username,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                if (data["sms-response"].user.adminRole == true) {
                    $.get(globals.settings.Server + '/mediaFolderSettings.view?scanNow');
                } else {
                    alert('You are not logged in as an admin user!');
                }
            }
        });
    };
    $scope.getIndexes = function () {
        var url, id;
        if (utils.getValue('mediaFolders')) {
            var folder = angular.fromJson(utils.getValue('mediaFolders'));
            id = folder.id;
        }
        if (id) {
            url = globals.BaseURL() + '/getIndexes.view?' + globals.BaseParams() + '&mediaFolderId=' + id;
        } else {
            url = globals.BaseURL() + '/getIndexes.view?' + globals.BaseParams();
        }
        $.ajax({
            url: url,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            done: function () { if (globals.settings.Debug) { console.log("DONE!"); } },
            error: function () { if (globals.settings.Debug) { console.log("ERROR!"); } },
            success: function (data) {
                var indexes = [];
                if (typeof data["sms-response"].indexes.index != 'undefined') {
                    if (data["sms-response"].indexes.index.length > 0) {
                        indexes = data["sms-response"].indexes.index;
                    } else {
                        indexes[0] = data["sms-response"].indexes.index;
                    }
                }
                $scope.index = [];
                angular.forEach(indexes, function (item) {
                    $scope.index.push($scope.mapIndex(item));
                });
                $scope.$apply();
            }
        });
    };
    $scope.mapIndex = function (data)
    {
        var element = data.element;
        var indexElement = [];
        
        if (element.length > 0)
        {
            indexElement = element;
        }
        else
        {
            indexElement[0] = element;
        }
        
        return new model.Index(data.name, indexElement);
    };
    $scope.getMediaDirectory = function (id) {
        $scope.selectedMediaBrowserSort = null;
        $scope.selectedIndex = id;
        var url = globals.BaseURL() + '/getMediaDirectory.view?' + globals.BaseParams() + '&id=' + id;
        $.ajax({
            url: url,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data)
            {
                var items = [];
                if (typeof data["sms-response"].directory.child != 'undefined')
                {
                    if (data["sms-response"].directory.child.length > 0)
                    {
                        items = data["sms-response"].directory.child;
                    }
                    else
                    {
                        items[0] = data["sms-response"].directory.child;
                    }
                    $scope.directory = [];
                    $rootScope.mediaElement = [];

                    angular.forEach(items, function (item)
                    {
                        if (item.mediaType === 'MEDIA_DIRECTORY' || item.mediaType === 'DIRECTORY')
                        {
                            $scope.directory.push($scope.mapDirectory(item));
                        }
                        else if (item.mediaType === 'AUDIO' || item.mediaType === 'VIDEO')
                        {
                            $rootScope.mediaElement.push($scope.mapMediaElement(item));
                        }
                    });
                    $scope.$apply();
                }
                else
                {
                    notifications.updateMessage('No Media Found!', true);
                }
            }
        });
    };
    $scope.mapDirectory = function (data)
    {
        var directory = data;
        var coverArtThumb, coverArtFull;
        
        if (typeof directory.coverArt !== 'undefined')
        {
            coverArtThumb = globals.BaseURL() + '/getCoverArt.view?' + globals.BaseParams() + '&size=160&id=' + directory.coverArt;
            coverArtFull = globals.BaseURL() + '/getCoverArt.view?' + globals.BaseParams() + '&id=' + directory.coverArt;
        }
        return new model.Directory(directory.id, directory.parent, directory.name, coverArtThumb, coverArtFull);
    };
    $scope.mapMediaElement = function (data)
    {
        var element = data;
        var url, track, discNumber;
        var coverArtThumb = '', coverArtFull = '', discSubtitle = '';
        
        if (typeof element.coverArt !== 'undefined')
        {
            coverartthumb = globals.BaseURL() + '/getCoverArt.view?' + globals.BaseParams() + '&size=60&id=' + element.coverArt;
            coverartfull = globals.BaseURL() + '/getCoverArt.view?' + globals.BaseParams() + '&id=' + element.coverArt;
        }
        if (typeof element.track === 'undefined') { track = '&nbsp;'; } else { track = element.track; }
        if (element.discNumber === null || element.discNumber === 'undefined') { discNumber = '&nbsp;'; } else { discNumber = element.discNumber; }
        if (element.discSubtitle === null) { discSubtitle = ''; } else { discSubtitle = element.discSubtitle; }
        
        // Workaround for browser caching issues
        var salt = Math.floor(Math.random() * 100000);
        url = globals.BaseURL() + '/stream.view?' + globals.BaseParams() + '&id=' + element.id + '&salt=' + salt;
        
        return new model.MediaElement(element.id, element.parent, element.mediaType, element.suffix, element.duration, element.title, element.album, element.artist, element.genre, element.year, discNumber, discSubtitle, track, coverArtThumb, coverArtFull, url, 0);
    };
    $scope.offset = 0;
    $scope.getMediaElementList = function (id, offset) {
        var url;
        $scope.selectedIndex = null;
        $scope.selectedMediaBrowserSort = id;
        if (offset == 'next') {
            $scope.offset = $scope.offset + globals.settings.MediaBrowserListSize;
        } else if (offset == 'prev') {
            $scope.offset = $scope.offset - globals.settings.MediaBrowserListSize;
        }
        if ($scope.offset > 0) {
            url = globals.BaseURL() + '/getMediaElementList.view?' + globals.BaseParams() + '&size=' + globals.settings.MediaBrowserListSize.toString() + '&type=' + id + '&offset=' + $scope.offset;
        } else {
            url = globals.BaseURL() + '/getMediaElementList.view?' + globals.BaseParams() + '&size=' + globals.settings.MediaBrowserListSize.toString() + '&type=' + id;
        }
        $.ajax({
            url: url,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data) {
                var items = [];
                if (typeof data["sms-response"].albumList.album !== 'undefined') {
                    if (data["sms-response"].albumList.album.length > 0) {
                        items = data["sms-response"].albumList.album;
                    } else {
                        items[0] = data["sms-response"].albumList.album;
                    }
                    $scope.directory = [];
                    angular.forEach(items, function (item, key) {
                        if (item.isDir) {
                            $scope.directory.push($scope.mapDirectory(item));
                        } else {
                            $rootScope.mediaElement.push($scope.mapMediaElement(item));
                        }
                    });
                    $scope.$apply();
                } else {
                    notifications.updateMessage('No Results Found!', true);
                }
            }
        });
    };
    $scope.getMediaElements = function (id, action)
    {
        $scope.selectedDirectory = id;
        var url = globals.BaseURL() + '/getMediaDirectory.view?' + globals.BaseParams() + '&id=' + id;
        $.ajax({
            url: url,
            method: 'GET',
            dataType: globals.settings.Protocol,
            timeout: globals.settings.Timeout,
            success: function (data)
            {
                var elements = [];
                if (typeof data["sms-response"].directory.child !== 'undefined')
                {
                    if (data["sms-response"].directory.child.length > 0)
                    {
                        elements = data["sms-response"].directory.child;
                    }
                    else
                    {
                        elements[0] = data["sms-response"].directory.child;
                    }
                    
                    if (action === 'add')
                    {
                        angular.forEach(elements, function (item, key)
                        {
                            $rootScope.queue.push($scope.mapMediaElement(item));
                        });
                        $scope.$apply();
                        $('body').layout().open('south');
                        notifications.updateMessage(elements.length + ' Tracks(s) Added to Queue', true);
                    }
                    else if (action === 'play')
                    {
                        $rootScope.queue = [];
                        angular.forEach(elements, function (item, key)
                        {
                            $rootScope.queue.push($scope.mapMediaElement(item));
                        });
                        var next = $rootScope.queue[0];
                        $scope.$apply(function ()
                        {
                            $rootScope.playMediaElement(false, next);
                        });
                        $('body').layout().open('south');
                    }
                    else
                    {
                        $rootScope.mediaElement = [];
                        var directories = [];
                        angular.forEach(elements, function (item, key)
                        {   
                            if (item.mediaType === 'MEDIA_DIRECTORY' || item.mediaType === 'DIRECTORY')
                            {
                                directories.push($scope.mapDirectory(item));
                            }
                            else if (item.mediaType === 'AUDIO' || item.mediaType === 'VIDEO')
                            {
                                $rootScope.mediaElement.push($scope.mapMediaElement(item));
                            }
                        });
                        if (directories.length > 0) {
                            $scope.directory = directories;
                        }
                        $scope.$apply();
                    }
                } else {
                    notifications.updateMessage('No Media Returned!', true);
                }
            }
        });
    };
    $scope.search = function () {
        var query = $('#Search').val();
        if (query != '') {
            var type = $('#SearchType').val();
            $.ajax({
                url: globals.BaseURL() + '/search.view?' + globals.BaseParams() + '&query=' + query,
                method: 'GET',
                dataType: globals.settings.Protocol,
                timeout: globals.settings.Timeout,
                success: function (data) {
                    if (data["sms-response"].searchResult !== "") {
                        var header;
                        var items = [];
                        if (type === 'audio') {
                            if (data["sms-response"].searchResult.audio !== undefined) {
                                if (data["sms-response"].searchResult.audio.length > 0) {
                                    items = data["sms-response"].searchResult.audio;
                                } else {
                                    items[0] = data["sms-response"].searchResult.audio;
                                }
                                $rootScope.mediaElement = [];
                                angular.forEach(items, function (item, key) {
                                    $rootScope.mediaElement.push($scope.mapMediaElement(item));
                                });
                                $scope.$apply();
                            }
                        }
                        if (type === 'album') {
                            if (data["sms-response"].searchResult.album !== undefined) {
                                if (data["sms-response"].searchResult.album.length > 0) {
                                    items = data["sms-response"].searchResult.album;
                                } else {
                                    items[0] = data["sms-response"].searchResult.album;
                                }
                                $scope.directory = [];
                                angular.forEach(items, function (item, key) {
                                    if (item.isDir) {
                                        $scope.directory.push($scope.mapDirectory(item));
                                    } else {
                                        $rootScope.mediaElement.push($scope.mapMediaElement(item));
                                    }
                                });
                                $scope.$apply();
                            }
                        }
                    }
                }
            });
        }
    };
    $scope.toggleAZ = function () {
        $scope.toggleSubmenu('#submenu_AZIndex', '#AZIndex', 'right', 44);
    };
    $scope.addMediaElementsToQueue = function () {
        if ($scope.selectedMediaElements.length !== 0) {
            angular.forEach($scope.selectedMediaElements, function (item, key) {
                $scope.queue.push(item);
                item.selected = false;
            });
            $('body').layout().open('south');
            notifications.updateMessage($scope.selectedMediaElements.length + ' Tracks(s) Added to Queue', true);
            $scope.selectedMediaElements.length = 0;
        }
    };

    /* Launch on Startup */
    $scope.getIndexes();
    /* End Startup */
});
